package com.shopping_assistant.view.overlays;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.drawable.Drawable;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.shopping_assistant.model.Shop;

public class SAItemizedOverlay extends ItemizedOverlay<SAOverlayItem>
{

	private List<SAOverlayItem> mOverlay = new ArrayList<SAOverlayItem>();
	private MyLocationOverlay myLocationOverlay;
	private Context context;
	private SAPopUp pop;
	private Shop currentlyShowing;

	public SAItemizedOverlay(Drawable defaultMarker, Context context, MyLocationOverlay myLocationOverlay) {
		super(boundCenterBottom(defaultMarker));
		this.myLocationOverlay = myLocationOverlay;
		this.context = context;
		pop = new SAPopUp(this, myLocationOverlay, context);
		
		populate();
	}

	public void addOverlay(SAOverlayItem overlay)
	{
		mOverlay.add(overlay);
		setLastFocusedIndex(-1);
		populate();
		pop.closeDialog();
		currentlyShowing = null;
	}

	public void clearOverlay()
	{
		mOverlay.clear();
		setLastFocusedIndex(-1);
		populate();
		pop.closeDialog();
		currentlyShowing = null;
	}
	
	public void tapItem(Shop shop) {
		
		Boolean found = false;
		SAOverlayItem item = null;
		
		if(currentlyShowing == null){
			
			for (int i = 0; i < mOverlay.size() && !found; i++) {
				item = mOverlay.get(i);

				if (item.getShop() == shop) {
					this.setFocus(item);

					currentlyShowing = shop;
					found = true;
					pop.showShopDialog(shop);
				}
			}
		}
	}

	@Override
	protected SAOverlayItem createItem(int i) {
		return mOverlay.get(i);
	}

	@Override
	protected boolean onTap(int index)
	{
		if(currentlyShowing == null) {
		
			SAOverlayItem overlayItem = mOverlay.get(index);

			Shop shop = overlayItem.getShop();

			currentlyShowing = shop;

			pop.showShopDialog(shop);
		}
		
		return true;
	}

	public void removeOverlay(SAOverlayItem overlay)
	{
		if(mOverlay.contains(overlay))
		{
			mOverlay.remove(overlay);
		}
		
		setLastFocusedIndex(-1);
		populate();
	}

	@Override
	public int size() {
		return mOverlay.size();
	}
	
	@Override
	public boolean onTap(GeoPoint p, MapView mapView) {
		return super.onTap(p, mapView);
	}

	public void unpopItem(Shop lastVisitedShop) {
		
		if(currentlyShowing == lastVisitedShop) {
			pop.closeDialog();
			currentlyShowing = null;
		}
	}

	public void dialogClosing() {
		currentlyShowing = null;
	}	
}
